﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 父窗口蒙版效果
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 当窗口失去焦点时会触发该事件
            this.Deactivated += MainWindow_Deactivated;
            // 当窗口获取焦点时会触发该事件
            this.LostFocus += MainWindow_LostFocus;
        }

        /// <summary>
        /// 窗口获取焦点 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void MainWindow_LostFocus(object sender, RoutedEventArgs e)
        {
        }

        /// <summary>
        /// 窗口失去焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void MainWindow_Deactivated(object sender, EventArgs e)
        {
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.MaskLayer.Visibility = Visibility.Visible;
            var childwindow = new Page() { Owner = this };
            childwindow.Closed += (s, t) =>
            {
                this.MaskLayer.Visibility = Visibility.Collapsed;
            };
            childwindow.ShowDialog();
        }


        /// <summary>
        /// 封装：显示子窗口并添加遮罩层
        /// </summary>
        /// <param name="parent">窗体</param>
        /// <param name="child">子窗体</param>
        /// <param name="maskLayer">遮罩层</param>
        public static void ShowChildWindowWithMask(Window parent, Window child, UIElement maskLayer)
        {
            if (maskLayer != null)
            {
                maskLayer.Visibility = Visibility.Visible; // 显示遮罩层
            }

            child.Owner = parent; // 设置父窗口
            child.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            // 子窗口关闭时隐藏遮罩层
            child.Closed += (s, e) =>
            {
                if (maskLayer != null)
                {
                    maskLayer.Visibility = Visibility.Collapsed;
                }
            };

            child.ShowDialog();
        }
    }
}
